//
//  LoginViewController.m
//  MZSystem
//
//  Created by 智障 on 2018/11/5.
//  Copyright © 2018 zerod. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginDetailView.h"

#import "HomeViewController.h"
#import "BaseNavigationController.h"

@interface LoginViewController ()
@property (nonatomic , strong)LoginDetailView *loginView;


@end
@implementation LoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.loginView];
    [self.loginView.loginIconImageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(SafeAreaValueHeight + 80);
    }];
}

- (LoginDetailView *)loginView{
    if (!_loginView) {
        _loginView = [Base_loadXibView loadFromXib:@"LoginDetailView" withCls:[LoginDetailView class]];
        [_loginView setFrame:CGRectMake(0, 0, ScrW, ScrH)];
        WS(weakSelf)
        _loginView.loginBlock = ^{
            [weakSelf compareToLogin];
        };
    }
    return _loginView;
}
//账号密码登录
-(void)compareToLogin{
    NSString *name = self.loginView.loginNameTF.text;
    if (name.length == 0) {
        SHOWERROR(@"请输入账号")
        return;
    }
    
    NSString *psw = self.loginView.pswTF.text;
    if (psw.length == 0) {
        SHOWERROR(@"请输入密码")
        return;
    }
    
    NSString*url=[NSString stringWithFormat:@"%@/login?username=%@&password=%@",URL_HOST,name,psw];
    [SendRequest postWithURL:url params:nil withCookie:NO success:^(id response) {
        
        int code = [response[@"code"] intValue];
        NSString *message = response[@"msg"];
        if(code==0){
            //保存cookie
            NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[NSURL URLWithString:url]];
            NSDictionary *Request = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
            [CoreArchive setStr:[Request objectForKey:@"Cookie"] key:COOKIE];
            
            //保存账号密码
//            NSDictionary*dic=[response[@"data"] mj_JSONObject];
            [CoreArchive setStr:name key:LoginName];
            [CoreArchive setStr:psw key:LoginPSW];
            AppRootViewController = [[UINavigationController alloc]initWithRootViewController:[HomeViewController new]];
        }else{
            SHOWERROR(message)
        }
        
    } fail:^(NSError *error) {
        SHOWERROR(showNetworkError)
    }];
    
}
@end
